<!-- src/views/Home.vue -->
<template>
  <div class="home">
    <h1>线路列表</h1> 
    <div>目标地址：{{ remoteIp}}  </div>
    <div>修改地址：<input v-model="remoteIp" /></div> 
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Comment</th>
            <th>IP</th>
            <th>Server</th>
            <th>Remark</th>
            <th>Command UUID</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in tableData" :key="item.id">
            <td>{{ item.id }}</td>
            <td><router-link :to="`/about?comment=${item.comment}`">{{ item.comment }}</router-link></td>
            <td>{{ item.ip }}</td>
            <td>{{ item.server }}</td>
            <td>{{ item.remark }}</td>
            <td>{{ item.command_uuid || '-' }}</td>
            <td class="action-buttons">
              <button class="send-btn" @click="handleSend(item)" :disabled="buttonDisabled[item.id]" :class="{ 'disabled-btn': buttonDisabled[item.id] }">开启收集</button>
              <button class="stop-btn" @click="handleStop(item)" :disabled="buttonDisabled[item.id]" :class="{ 'disabled-btn': buttonDisabled[item.id] }">停止收集</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeMount } from 'vue';

// 表格数据
const tableData = ref([])
// 按钮禁用状态管理
const buttonDisabled = ref({});

const remoteIp = defineModel('remoteIp', {
  type: String,
  default: '118.193.28.18'
})

onMounted(async () => {
  try {
    const response = await fetch('/api/v3/command/confirmList')
    const data = await response.json()
    if (data.success) {
      tableData.value = data.result
    }
  } catch (error) {
    console.error('Error fetching data:', error)
  }
})

// 日期格式化辅助函数
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 发送按钮点击事件
const handleSend = async (item) => {
  // 禁用按钮11秒
  buttonDisabled.value[item.id] = true;
  setTimeout(() => {
    buttonDisabled.value[item.id] = false;
  }, 11000);
  try {
    // 根据GRE字段构建shell命令
    let shell = '';
    switch (item.remark) {
      case 'server':
        shell = "nohup tcpdump -i any port 12345 >> /tmp/watch.log &";
        break;
      case 'tunnel':
        shell = `nohup tcpdump -i ${item.server} host ${remoteIp.value} >> /tmp/watch.log &`;
        break;
      default:
        shell = `nohup tcpdump -i eth0 port 12345 >> /tmp/watch.log &`;
        break;
    } 

    const response = await fetch(`/api/v3/command/add`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: 'start',
        comment: item.comment,
        ip: [item.ip],
        shell: shell
      })
    });

    const result = await response.json();
    console.log('Start request result:', result);
    if (!response.ok) throw new Error('Request failed');
    alert('Start command sent successfully');
  } catch (error) {
    console.error('Error sending start command:', error);
    alert('Failed to send start command');
  }
};

// 停止按钮点击事件
const handleStop = async (item) => {
  // 禁用按钮11秒
  buttonDisabled.value[item.id] = true;
  setTimeout(() => {
    buttonDisabled.value[item.id] = false;
  }, 11000);
  try {
    const response = await fetch('/api/v3/command/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: 'stop',
        comment: item.comment,
        ip: [item.ip],
        shell: ''
      })
    });
    const result = await response.json();
    console.log('Stop request result:', result);
    if (!response.ok) throw new Error('Request failed');
    alert('Stop command sent successfully');
  } catch (error) {
    console.error('Error sending stop command:', error);
    alert('Failed to send stop command');
  }
}
</script>

<style scoped>
.table-container {
  margin: 20px 0;
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 800px;
}

.data-table th,
.data-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.data-table th {
  background-color: #f5f5f5;
  font-weight: bold;
  color: #333;
}

.data-table tr:hover {
  background-color: #f9f9f9;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.send-btn {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.send-btn:hover {
  background-color: #359469;
}

.disabled-btn {
  background-color: #cccccc !important;
  cursor: not-allowed;
  opacity: 0.7;
  pointer-events: none;
}

.stop-btn {
  background-color: #f56c6c;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.stop-btn:hover {
  background-color: #e45656;
}
</style>